/**
 * 
 */
package org.t2.game.server.module.data.service.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.gaming.tool.GsonUtil;
import org.gaming.tool.ListMapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.t2.game.server.module.bag.model.Bag;
import org.t2.game.server.module.bag.service.BagService;
import org.t2.game.server.module.data.model.Data;
import org.t2.game.server.module.data.saver.PlayerHeroNumSaver;
import org.t2.game.server.module.data.service.DataParserService;
import org.t2.game.server.module.data.struct.HeroData;
import org.t2.game.server.module.data.struct.HeroItem;
import org.t2.game.server.module.hero.model.Hero;
import org.t2.game.server.module.hero.service.HeroService;

/**
 * 
 */
@Component
public class HeroParserService extends DataParserService {
	
	@Autowired
	private BagService bagService;
	@Autowired
	private PlayerHeroNumSaver playerHeroNumSaver;
	@Autowired
	private HeroService heroService;

	@Override
	public String dataType() {
		return "hero";
	}

	@Override
	public void parser(long playerId, List<Data> datas, String reason) {
		Bag bag = bagService.getEntity(playerId);
		boolean needUpdate = false;
		
		Map<Integer, Hero> heroMap = ListMapUtil.listToMap(heroService.getEntities(playerId), Hero::getIdentity);
		
		List<Hero> newHeros = new ArrayList<>();
		for(Data data : datas) {
			HeroData heroData = GsonUtil.parseJson(data.getPlaintext(), HeroData.class);
			if(heroData.getHeroData() == null) {
				continue;
			}
			if(heroData.getHeroData().size() != bag.getHeroNum()) {
				playerHeroNumSaver.setNumber(bag, reason, heroData.getHeroData().size());
				needUpdate = true;
			}
			for(HeroItem heroItem : heroData.getHeroData()) {
				Hero hero = heroMap.get(heroItem.getId());
				if(hero == null) {
					hero = new Hero();
					hero.setPlayerId(playerId);
					hero.setIdentity(heroItem.getId());
					newHeros.add(hero);
					heroMap.put(hero.getIdentity(), hero);
				}
			}
		}
		if(needUpdate) {
			bagService.update(bag);
		}
		if(!newHeros.isEmpty()) {
			heroService.insert(newHeros);
		}
	}
	
}
